package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.DepartmentVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.WarehouseDao;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WarehouseSubDataModel;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/2/15 14:53
 * @since v1.0
 */
@Service("warehouseModel")
public class WarehouseModelImpl implements WarehouseModel {

    private static final Logger LOG = LoggerFactory.getLogger(WarehouseModelImpl.class);
    @Resource
    private WarehouseDao warehouseDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private WarehouseSubDataModel warehouseSubDataModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private EsHelper esHelper;

    /**
     * 仓库数据单条查询
     *
     * @param key    主键ID
     * @param corpid 公司ID
     * @return Integer
     * @author feng.zheng
     * @date 2019/2/15 20:27
     * @since v1.0
     */
    @Override
    public WarehouseEntityExt getByKey(Long key, String corpid) {
        WarehouseEntityExt entityExt = warehouseDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        return entityExt;
    }

    /**
     * 获取所有的仓库 默认增加一项【全部仓库】
     *
     * @param corpid 公司ID
     * @return Integer
     * @author feng.zheng
     * @date 2019/2/15 20:27
     * @since v1.0
     */
    @Override
    public JSONArray fillWarehouseArray(String corpid) {
        JSONArray warehouseArray = getWarehouseArray(corpid);
        //默认增加一项【全部仓库】
        JSONObject defaultWarehouseObj = new JSONObject();
        defaultWarehouseObj.put("warehouseId", -1);
        defaultWarehouseObj.put("warehouseName", I18nMessageUtil.getMessage(I18nStringConstant.ALL_WAREHOUSE));
        warehouseArray.add(0, defaultWarehouseObj);
        return warehouseArray;
    }
    /**
     * 获取所有的仓库
     *
     * @author GuoJun.HU
     * @date 2017/12/13 20:35
     * @since 2.0
     */
    @Override
    public JSONArray getWarehouseArray(String corpid) {
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", corpid);
        param.put("del", 0);
        List<WarehouseEntityExt> warehouseList = findEntitys(param);

        JSONArray warehouseArray = new JSONArray();
        for (WarehouseEntityExt warehouse : warehouseList) {
            long warehouseId = warehouse.getId();
            JSONObject dataList = warehouse.getData();
            String warehouseName = dataList.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
            JSONObject warehouseObj = new JSONObject();
            warehouseObj.put("warehouseId", warehouseId);
            warehouseObj.put("warehouseName", warehouseName);
            warehouseArray.add(warehouseObj);
        }

        return warehouseArray;
    }

    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(WarehouseEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = warehouseDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_WAREHOUSE);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        return success;
    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(WarehouseEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = warehouseDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = warehouseDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_WAREHOUSE);
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }

        return success;
    }

    /**
     * 获取符合查询条件的记录
     *
     * @param param 查询条件
     * @return 符合查询条件的记录
     */
    @Override
    public List<WarehouseEntityExt> findEntitys(Map<String, Object> param) {
        List<WarehouseEntityExt> entitys = warehouseDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        }
        return entitys;
    }

    @Override
    public Map<Long, JSONObject> findWarehouseObjMapByIdIn(List<Long> idIn, String corpid) {
        Map<Long, JSONObject> result = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (idIn.isEmpty()) {
            return result;
        }
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", corpid);
        params.put("idIn", idIn);
        List<WarehouseEntityExt> warehouseEntitys = findEntitys(params);
        if (warehouseEntitys != null) {
            for (WarehouseEntityExt warehouseEntityExt : warehouseEntitys) {
                JSONObject dataList = warehouseEntityExt.getData();
                Long wId = warehouseEntityExt.getId();
                JSONObject warehouseObj = new JSONObject();
                warehouseObj.put(StringConstant.SAAS_LINK_BUSINESS_ID, wId);
                warehouseObj.put(StringConstant.VALUE, dataList.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
                result.put(wId, warehouseObj);
            }
        }
        return result;
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return warehouseDao.getEntitysCount(param);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> dataIdIn, String corpid) throws XbbException {
        Integer integer = warehouseDao.deleteBatch(dataIdIn, corpid);
        paasEsModel.deleteBatch(dataIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_WAREHOUSE);

        paasFormSubDataModel.deleteBatchByDataId(dataIdIn, corpid, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_WAREHOUSE);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_WAREHOUSE_SUB);
        return warehouseDao.deleteByKey(key,corpid);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = warehouseDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_WAREHOUSE);
        }
        if (!subList.isEmpty()) {
            warehouseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = warehouseDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_WAREHOUSE, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            warehouseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.WAREHOUSE, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatchImmediately(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = warehouseDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_WAREHOUSE, WriteRequest.RefreshPolicy.NONE);
        }
        if (!subList.isEmpty()) {
            warehouseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return warehouseDao.findEntitys(param);
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {

    }

    @Override
    public List<Long> getWarehouseIdsByPermission(UserVO loginUser, Set<DepartmentVO> depSet) throws XbbException {
        String corpid = loginUser.getCorpid();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        if (!loginUser.isMaxDataPermission(true)){
            List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditionList, loginUser, XbbRefTypeEnum.WAREHOUSE.getCode(),depSet);
            EsUtil.parseShouldCondition(boolQueryBuilder,shouldConditionList,"",corpid,XbbRefTypeEnum.WAREHOUSE.getCode());
        }
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,PaasFormDataEntityExt.class,Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
            dataIdList.add(entityExt.getDataId());
        }
        if (dataIdList.isEmpty()){
            dataIdList.add(-1L);
        }
        return dataIdList;
    }
}
